package com.cec.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cec.context.BaseContext;
import com.cec.dto.UserDTO;
import com.cec.dto.UserLoginDTO;
import com.cec.entity.User;
import com.cec.exception.AccountException;
import com.cec.exception.OperationDataException;
import com.cec.mapper.user.UserMapper;
import com.cec.result.Result;
import com.cec.result.ResultCode;
import com.cec.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userLoginDTO.getUserName())
                .eq("user_pwd", userLoginDTO.getUserPwd());
        User user = baseMapper.selectOne(wrapper);
        if (user == null)
            throw new AccountException(ResultCode.BAD_CREDENTIALS);
        return user;
    }

    @Override
    public Result getUserInfo() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", BaseContext.getCurrentId());
        User user = baseMapper.selectOne(wrapper);
        if (user == null)
            throw new AccountException(ResultCode.USER_ERROR);
        return Result.success(user);
    }

    @Override
    public Result updateUser(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        int i = baseMapper.updateById(user);
        if (i<=0)
            throw new AccountException(ResultCode.USER_ERROR);
        return Result.success("修改成功");
    }

    @Override
    public Result registerUser(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",userDTO.getUserName());
        User user1 = baseMapper.selectOne(wrapper);
        if (user1!=null)
            throw new AccountException(ResultCode.USER_PRESENCE);
        int i = baseMapper.insert(user);
        if (i>0)
            return Result.success();
        throw new OperationDataException(ResultCode.OPERATION_DATA_ERROR);
    }
}
